package com.itaming.lycheeframework.support.properties;

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * 扩展的配置源工厂类
 * <p>
 * 在默认的配置源工厂类{@link DefaultPropertySourceFactory}基础上，增加了额外支持：
 * <blockquote>
 * <li>
 * yaml格式：yml, yaml
 * </li>
 * </blockquote>
 *
 * @author A.Ming
 */
public class ExtendedPropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 获取资源
        Resource res = resource.getResource();

        // 处理yaml格式
        if (isYaml(res)) {
            YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
            List<PropertySource<?>> load = yamlPropertySourceLoader.load(getNameForResource(name, res), res);
            return load.get(0);
        }

        // 其他格式使用默认处理
        return super.createPropertySource(name, resource);
    }

    /**
     * 判断是否是yaml文件
     *
     * @param resource 资源
     * @return boolean
     */
    private boolean isYaml(Resource resource) {
        String filename = resource.getFilename();
        return StringUtils.endsWithIgnoreCase(filename, ".yml") || StringUtils.endsWithIgnoreCase(filename, ".yaml");
    }

    /**
     * 获取资源名
     *
     * @param resource 资源
     * @return 资源名
     */
    private static String getNameForResource(String name, Resource resource) {
        if (StringUtils.hasText(name)) {
            return name;
        }

        String newName = resource.getDescription();
        if (!StringUtils.hasText(newName)) {
            String var10000 = resource.getClass().getSimpleName();
            newName = var10000 + "@" + System.identityHashCode(resource);
        }

        return newName;
    }

}
